package cn.tedu.charging.order.config;


import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
public class MqttClientConfiguration {
    @Autowired
    private MqttContext mqttContext;
    @Value("${charging.emqx.address}")
    private String address;
    //charging.emqx.username
    @Value("${charging.emqx.username}")
    private String username;
    //charging.emqx.password
    @Value("${charging.emqx.password}")
    private String password;
    @Bean
    public MqttClient mqttClient(){
        MqttClient mqttClient = null;
        try {
            mqttClient=new MqttClient(address,"charging-client"+ UUID.randomUUID().toString());
            MqttConnectOptions  options=new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            mqttClient.setCallback(new MqttConsumer(mqttClient,mqttContext));
            mqttClient.connect(options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mqttClient;
    }
}
